import {take,call,put,select} from 'redux-saga/effects'
import {get, post, put_http} from '../axios'
import {actionsTypes as IndexActionTypes} from '../reducers'
import {actionsTypes as MilestoneActionTypes} from '../reducers/milestone'
import history from '../history';

export function* get_list (project_id) {
    yield put({type: IndexActionTypes.FETCH_START});
    try {
        return yield call(get, `/mem/project-milestone/${project_id}`);
    } catch (err) {
        yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '网络请求错误', msgType: 'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END})
    }
}

export function* getMilestoneListFlow () {
    while (true){
        let req = yield take(MilestoneActionTypes.GET_MILESTONE);
        let res = yield call(get_list, req.project_id);
        if (res&&res.success) {
            yield put({type: MilestoneActionTypes.RES_MILESTONE, data: res.data})
        } else {
            yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: res.msg, msgType: 'fail'});
        }
    }
}

export function* set_milestone (data, project_id, id) {
    yield put({type: IndexActionTypes.FETCH_START});
    try {
        if (id) {
            return yield call(put_http, `/mem/project-milestone/${id}`, data);
        } else {
            return yield call(post, `/mem/project-milestone/${project_id}`, data);
        }
    } catch (err) {
        yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '网络请求错误', msgType: 'fail'});
    } finally {
        yield put({type: IndexActionTypes.FETCH_END})
    }
}

export function* setMilestoneFlow () {
    while (true){
        let req = yield take(MilestoneActionTypes.SET_MILESTONE);
        let project_id = req.project_id? req.project_id : undefined
        console.log(req.data)
        let res = yield call(set_milestone, req.data, project_id);
        if (res&&res.success) {
            yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: '设置成功', msgType: 'success'});
            yield call( ()=>setTimeout( function () {
                history.go(-1)
            }, 1000))
        } else {
            yield put({type: IndexActionTypes.SET_MESSAGE, msgContent: res.msg, msgType: 'fail'});
        }
    }
}